<template>
  <base-container>
    <a-spin :spinning="loading">
      <div class="desc">
        <p class="text-lg mb-2 font-bold">以下是套餐说明：</p>
        <p class="text-lg mb-2">1.套餐支持多选，选择后本公司员工的查价页面将会新增对应套餐；</p>
        <p class="text-lg">2.保存后查价页面即时生效，请避免在查价高峰期调整套餐配置；</p>
        <h3 class="text-lg">请选择您要配置的套餐:</h3>
      </div>
      <div class="flex">
        <div v-for="(item, i) in premiums" :key="i" class="mr-4">
          <PremiumCard
            :title="item.premiumName"
            :select="item.selected"
            :count="item.percent"
            @click="handleClick(item)"
          />
        </div>
      </div>
      <a-button type="primary" class="mt-6" :loading="configLoading" @click="handleSubmit">提交</a-button>
    </a-spin>
  </base-container>
</template>

<script lang="ts" setup>
import { onMounted } from 'vue'
import BaseContainer from '@/components/base-container/index.vue'
import PremiumCard from '@/views/premium/components/PremiumCard.vue'
import getPremiumList from '@/services/premium/getPremiumList'
import type { EnhancePremium } from '@/core/interfaces/premium'
import getPremiumConfig from '@/services/premium/getPremiumConfig'
import { useMainStore } from '@/store/useMainStore'
import updatePremium from '@/services/premium/updatePremium'
import { message, Modal } from 'ant-design-vue'

const mainStore = useMainStore()
const [premiums, fetchPremiumList, loading] = getPremiumList()
const [, fetchPremiumConfig] = getPremiumConfig()
const [, submitPremiumData, configLoading] = updatePremium()

function handleClick(record: EnhancePremium) {
  record.selected = !record.selected
}

function handleSubmit() {
  Modal.confirm({
    title: '提示',
    content: '是否确定提交',
    async onOk() {
      const [err, res] = await submitPremiumData({
        proxyId: mainStore.proxyId,
        premiumRatioIds: premiums.value.filter((item) => item.selected).map((item) => item.id)
      })

      if (!err) {
        message.success(res.data.msg)
        loadPremiumConfig()
      }
    }
  })
}

async function loadPremiumConfig() {
  const [err, res] = await fetchPremiumConfig({
    proxyId: mainStore.proxyId
  })

  if (!err) {
    premiums.value.forEach((item) => {
      item.selected = !!res.data.data.find((d) => {
        return d.id === item.id
      })
    })
  }
}

async function loadPremium() {
  await fetchPremiumList()
}

onMounted(async () => {
  await loadPremium()
  await loadPremiumConfig()
})
</script>

<script lang="ts">
export default {
  name: 'Premium'
}
</script>
